package com.wangzha.business.ctrl;

import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Record;
import com.wangzha.business.service.DeviceGroupService;
import com.wangzha.business.service.DeviceService;
import com.wangzha.common.base.BaseController;
import com.wangzha.common.model.Device;
import com.wangzha.common.model.DeviceGroup;
import com.wangzha.common.model.SysUser;
import com.wangzha.common.vo.Grid;
import com.wangzha.portal.core.service.SysUserService;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;

@Path("/device")
public class DeviceController extends BaseController {
    @Inject
    DeviceService deviceService;

    @Inject
    DeviceGroupService deviceGroupService;

    @Inject
    SysUserService sysUserService;

    public void index() {
        SysUser sysUser = sysUserService.findByUserCode(getVisitor().getCode());
        Integer port = 0;
        if (getParaToInt("type") != null) {
            if (getParaToInt("type") == 1) {
                port = sysUser.getPort();
            } else {
                port = sysUser.getTryPort();
            }
        }
        setAttr("port", NumberUtils.toInt(port + ""));
        setAttr("deviceGroupList", deviceGroupService.findByUserCode(getVisitor().getCode()));
        setAttr("type", getParaToInt("type"));
        render("index.html");
    }


    private Map<Long, String> toDeviceGroupMap(List<DeviceGroup> deviceGroupList) {
        Map<Long, String> map = null;
        if (CollectionUtils.isNotEmpty(deviceGroupList)) {
            map = new HashMap<>();
            for (DeviceGroup deviceGroup : deviceGroupList) {
                map.put(deviceGroup.getId(), deviceGroup.getName());
            }
        }
        return map;
    }

    public void list() {
        String userCode = null;
        if (StringUtils.isNotBlank(getVisitor().getCode()) && !getVisitor().getCode().equals("superadmin")) {
            userCode = getVisitor().getCode();
        }

        Grid grid = deviceService.queryForListByParam(getParaToInt("pageNumber", 1),
                getParaToInt("pageSize", 10), getParaToLong("groupId"), getPara("activationCode"),
                getPara("deviceName"), userCode, getParaToInt("type"));

        if (grid != null && CollectionUtils.isNotEmpty(grid.getList())) {
            List<Record> deviceList = (List<Record>) grid.getList();
            Map<Long, String> map = toDeviceGroupMap(deviceGroupService.findByUserCode(getVisitor().getCode()));
            for (Record device : deviceList) {
                device.set("group_name", map.get(device.getLong("group_id")));
                if (device.getDate("effective_time") != null) {
                    device.set("diff_date", getDistanceTime(new Date(), device.getDate("effective_time")));
                }
            }
            grid.setList(deviceList);
        }
        renderJson(grid);
    }

    public void edit() {
        setAttr("device", deviceService.findById(getPara(0)));
        setAttr("deviceGroupList", deviceGroupService.findByUserCode(getVisitor().getCode()));
        render("edit.html");
    }

    public void update() {
        Device entity = getBean(Device.class);
        entity.update();
        setAttr("deviceGroupList", entity);
        render("edit.html");
    }

    public void add() {
        setAttr("deviceGroupList", deviceGroupService.findByUserCode(getVisitor().getCode()));
        setAttr("type", getParaToInt("type"));
        render("add.html");
    }

    public void save() {

        SysUser user = sysUserService.findByUserCode(getVisitor().getCode());
        Integer type = getParaToInt("type");
        boolean flag = (type == 1 && user.getPort() > 0) || (type == 2 && user.getTryPort() > 0);
        if (flag) {
            Device deviceBean = getBean(Device.class);
            Device device = deviceService.findByActivationCode(deviceBean.getActivationCode());
            if (device == null) {
                Calendar calendar = Calendar.getInstance();
                if (getParaToInt("type") == 1) {
                    user.setPort(user.getPort() - 1);
                } else {
                    user.setTryPort(user.getTryPort() - 1);
                }
                calendar.add(Calendar.DAY_OF_MONTH, getParaToInt("addDays"));
                deviceBean.setEffectiveTime(calendar.getTime());
                deviceBean.setType(getParaToInt("type"));

                deviceBean.setCreateTime(new Date());
                deviceBean.setUpdateTime(new Date());
                deviceBean.setUserCode(getVisitor().getCode());
                deviceBean.save();

                user.update();

                setAttr("device", deviceBean);
                setAttr("deviceGroupList", deviceGroupService.findByUserCode(getVisitor().getCode()));
                render("add.html");
            } else {
                setException("该设备已存在");
                render("add.html");
            }
        } else {
            setException("允许添加设备数量不足");
            render("add.html");
        }
    }


    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param d1 时间参数 1 格式：1990-01-01 12:00:00
     * @param d2 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public static String getDistanceTime(Date d1, Date d2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long time1 = d1.getTime();
        long time2 = d2.getTime();
        long diff;
        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            return "已过期";
        }
        day = diff / (24 * 60 * 60 * 1000);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        return day + "天" + hour + "小时" + min + "分";
    }


    public void delete() {
        List<Device> deviceList = (List<Device>) deviceService.findByIds(getIds());
        for (Device device : deviceList) {
//           // 删除后要把端口返回
//           Db.tx(() -> sysUserService.updatePortByUserCode(device.getUserCode(), 1) &&
            deviceService.deleteById(device.getId() + "");
        }
        renderJson(suc());
    }

    public static void main(String[] args) {
        try {
            Date date1 = DateUtils.parseDate("2013-11-13 11:25:12", "yyyy-MM-dd HH:mm:ss");
            Date date2 = DateUtils.parseDate("2013-11-14 11:20:12", "yyyy-MM-dd HH:mm:ss");
            System.out.println(getDistanceTime(date2, date1));
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

